from django.conf import settings
from django.db import models

import facebook

import core.models

import datetime

class User(core.models.BaseModel):
  
  SESSION_KEY = '_fb_connect_user'
  
  # User's Facebook ID, this should never change
  fbid = models.CharField(primary_key=True)
  
  # The only data required to access the Facebook API
  access_token = models.CharField(max_length=255)
  
  # Access permissions the user has granted us
  permissions = models.CommaSeparatedIntegerField(max_length=255)
  
  # Data cached from the user's Facebook profile
  first_name = models.CharField(blank=True, max_length=50)
  last_name = models.CharField(blank=True, max_length=50)
  
  # Additional data
  #   Nothing here yet...
  
  @staticmethod
  def logout(request):
    """Deletes the user's current session"""
    request.session.flush()
    if hasattr(request, 'user'):
      request.user = None
  
  def login(self, request):
    """Login a user by storing his information in the current session"""
    if User.SESSION_KEY in request.session:
      if request.session[User.SESSION_KEY] != self.fbid:
        # To avoid reusing another user's session, create a new, empty
        # session if the existing session corresponds to a different
        # authenticated and user.
        request.session.flush()
    else:
      request.session.cycle_key()
    request.session[User.SESSION_KEY] = self.fbid
    
  def getPermissions(self):
    """Get the Facebook API permissions granted by this user."""
    if not self.cached_permissions:
      perm_indices = map(int, self.permissions.split(','))
      perms = set()
      for i in perm_indices:
        perms.add(auth.permissions.ALL_PERMISSIONS[i])
      self.cached_permissions = perms
    return self.cached_permissions
    
  def hasPermission(self, perm):
    perms = self.getPermissions()
    return perm in perms
  
  def checkPermission(self, perms):
    return [perm for perm in perms if not self.hasPermission(perm)]
  
  def refresh(self, access_token):
    """Connect to the Facebook API to refresh this user's data.
    Params:
      access_token: String, token to access the Facebook API.
    Returns:
      The updated User object.
    """
    self.access_token = access_token
    graph = facebook.GraphAPI(self.access_token)
    profile = graph.get_object("me")
    if (self.fbid != profile['id']):
      raise Exception('ID Mismatch')
    self.first_name = profile['first_name']
    self.last_name = profile['last_name']
    self.save()
    return self    
	